package cn.edu.zafu.bigdata.x.yaojy;
import cn.hutool.core.lang.copier.SrcToDestCopier;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class UDPTimeClient {
    private static final String SERVER_ADDRESS = "192.168.16.2";
    private static final int SERVER_PORT = 12345;
    public static void main(String[] args) {
        try(DatagramSocket socket = new DatagramSocket()){
            String requestMessage = "Request time";
            byte[] sendData = requestMessage.getBytes();
            InetAddress serverAddress = InetAddress.getByName(SERVER_ADDRESS);
            DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,serverAddress,SERVER_PORT);
            socket.send(sendPacket);
            byte[] buffer = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(buffer,buffer.length);
            socket.receive(receivePacket);
            String currentTime = new String(receivePacket.getData(),0,receivePacket.getLength());
            System.out.println("Received time from server: " + currentTime);
            LocalDateTime formattedTime = LocalDateTime.parse(currentTime,DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss"));
            System.out.println("Formatted received time:" + formattedTime);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
